import Phaser from "phaser";
import { Card } from "./Card";
import { MainScene } from "../scenes";
import { polygon } from "../enums";
import { ThreePolygon } from "./ThreePolygon";
import { FourPolygon } from "./FourPolygon";

export class Handler extends Phaser.Physics.Arcade.Sprite {

    somethingInHand: boolean = false
    currentTexture: string | Phaser.Textures.Texture
    card: Card

    constructor(scene: MainScene) {
        super(scene, 0, 0, '')
        scene.add.existing(this)
        scene.physics.add.existing(this)
        this.setInteractive()

        this.visible = false
        this.disableBody()

        this.on('pointerdown', (pointer: any) => {
            const { button, downX, downY } = pointer
            const res = scene.chooseArea(downX, downY)
            if (button === 0 && res !== false) {
                const [row, col, positionX, positionY] = res
                this.card.startCooldown()
                scene.subDiamond(50)

                if (this.currentTexture === polygon.three) {
                    scene.polygons.add(new ThreePolygon(scene, positionX, positionY, row, col))
                } else if (this.currentTexture === polygon.four) {
                    scene.polygons.add(new FourPolygon(scene, positionX, positionY, row, col))
                }

                this.visible = false
                this.disableBody()
                this.somethingInHand = false

            }
            if (button !== 0) {
                this.visible = false
                this.disableBody()
                this.somethingInHand = false
            }

        })
    }

    protected preUpdate(time: number, delta: number): void {
        super.preUpdate(time, delta)
        const pointer = this.scene.input.activePointer
        this.x = pointer.x
        this.y = pointer.y
    }

    toActive(texture: string | Phaser.Textures.Texture, card: Card) {
        this.somethingInHand = true
        this.currentTexture = texture
        this.setTexture(texture)
        this.visible = true
        this.enableBody()
        this.card = card
    }
}